package kr.co.goodwilldd.framework.security.impl;

import kr.co.goodwilldd.framework.security.IAuthenticationFacade;
import kr.co.goodwilldd.framework.security.ReloadAuthentication;
import kr.co.goodwilldd.framework.security.model.CustomUser;
import kr.co.goodwilldd.framework.security.model.UserRegistration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class AuthenticationFacade implements IAuthenticationFacade {

	@Override
	public Authentication getAuthentication() {
		return SecurityContextHolder.getContext().getAuthentication();
	}

	@Override
	public String getUsername() {
		try {
			if (getAuthentication().getPrincipal() instanceof String) {
				// return (String) getAuthentication().getPrincipal();
				return null;
			} else if (getAuthentication().getPrincipal() instanceof CustomUser) {
				return ((CustomUser) getAuthentication().getPrincipal())
						.getUsername();
			} else {
				return null;
			}
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public CustomUser getUser() {
		try {
			return (CustomUser) getAuthentication().getPrincipal();
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public UserRegistration getUserdata() {
		UserRegistration userdata = null;
		try {
			userdata = ((CustomUser) getAuthentication().getPrincipal())
					.getUserdata();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return userdata;
	}
	
//  TODO Spring Security Dependency
//	@Autowired
//	ReloadAuthentication reloadAuthentication;

	@Override
	public void reloadUserAuthentication(String username) {
		//reloadAuthentication.reloadAuthentication(username);
	}
}
